﻿using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WMS.Model;
using WMS.Repository.IRepository;
using WMS.Service.IService;

namespace WMS.Service
{
    internal class DepartmentService : BaseServices<DepartmentModel>, IDepartmentService
    {
        private readonly IDepartmentRepository _departmentRepository;

        public DepartmentService(IBaseRepository<DepartmentModel> repository,
            ILogger<BaseServices<DepartmentModel>> logger,
            IDepartmentRepository departmentRepository) : base(repository, logger)
        {
            _departmentRepository = departmentRepository;
        }

        /// <summary>
        /// 添加部门
        /// </summary>
        public async Task<(bool Success, string Message)> AddDepartmentAsync(string departmentName, string departmentDesc)
        {
            try
            {
                var department = await _departmentRepository.GetDepartmentNameAsync(departmentName);
                if (department != null)
                {
                    return (false, "部门已存在");
                }

                DepartmentModel model = new DepartmentModel()
                {
                    DepartmentName = departmentName,
                    DepartmentDesc = departmentDesc,
                    CreateTime = DateTime.Now,
                };

                bool result = await _repository.AddAsync(model);
                if (result)
                {
                    return (true, "添加成功！");
                }
                else
                {
                    return (false, "添加失败，请重新尝试！");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"添加部门失败 - 部门名称: {departmentName}");
                throw;
            }
        }

        /// <summary>
        /// 分页查询部门列表
        /// </summary>
        public async Task<PageResult<DepartmentModel>> GetDepartmentPagedListAsync(DepartmentQueryRequest request)
        {
            try
            {
                if (request.PageSize > 100)
                {
                    request.PageSize = 100;
                }
                return await _departmentRepository.GetDepartmentPagedListAsync(request);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "部门分页查询失败");
                throw;
            }
        }

        /// <summary>
        /// 修改部门
        /// </summary>
        public async Task<(bool Success, string Message)> UpdateDepartmentAsync(long id, string departmentName, string departmentDesc, byte status, long parentId, long Minister)
        {
            try
            {
                var department = await _repository.GetAsync(id);
                if (department == null)
                {
                    return (false, "部门不存在！");
                }

                department.DepartmentName = departmentName;
                department.DepartmentDesc = departmentDesc;
                department.UpdateTime = DateTime.Now;
                department.Status = status;
                department.ParentId = parentId;
                department.Minister = Minister;

                bool result = await _repository.UpdateAsync(department);
                if (result)
                {
                    return (true, "修改成功！");
                }
                else
                {
                    return (false, "修改失败，请重新尝试！");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"修改部门失败 - 部门ID: {id}");
                throw;
            }
        }

        /// <summary>
        /// 启用禁用部门
        /// </summary>
        public async Task<(bool Success, string Message)> UpdateDepartmentStatusAsync(long id)
        {
            try
            {
                var department = await _repository.GetAsync(id);
                if (department == null)
                {
                    return (false, "部门不存在！");
                }

                department.Status = (byte)(department.Status == 0 ? 1 : 0);
                bool result = await _repository.UpdateAsync(department);
                if (result)
                {
                    return (true, "操作成功！");
                }
                else
                {
                    return (false, "操作失败，请重新尝试！");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新部门状态失败 - 部门ID: {id}");
                throw;
            }
        }

        /// <summary>
        /// 批量启用停用部门
        /// </summary>
        public async Task<(bool Success, string Message)> UpdateDepartmentsStatusAsync(List<long> ids)
        {
            try
            {
                var successCount = 0;
                var notFoundIds = new List<long>();
                var failedIds = new List<long>();

                foreach (var id in ids)
                {
                    try
                    {
                        var department = await _repository.GetAsync(id);
                        if (department == null)
                        {
                            notFoundIds.Add(id);
                            continue;
                        }

                        department.Status = (byte)(department.Status == 0 ? 1 : 0);
                        bool result = await _repository.UpdateAsync(department);
                        if (result)
                        {
                            successCount++;
                        }
                        else
                        {
                            failedIds.Add(id);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogError(ex, $"处理部门状态失败 - 部门ID: {id}");
                        failedIds.Add(id);
                    }
                }

                var message = $"操作完成：成功 {successCount} 个，失败 {failedIds.Count} 个，未找到 {notFoundIds.Count} 个";
                return (successCount > 0, message);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"批量更新部门状态失败 - 部门数量: {ids?.Count ?? 0}");
                throw;
            }
        }

        /// <summary>
        /// 获取部门下拉框
        /// </summary>
        public async Task<object> GetDepartmentDropdownBoxAsync(long departmentId)
        {
            try
            {
                var departmentModels = await _departmentRepository.GetDepartmentDropdownBoxAsync(departmentId);
                return departmentModels.Select(x => new { x.Id, x.DepartmentName }).ToList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"获取部门下拉框失败 - 排除部门ID: {departmentId}");
                throw;
            }
        }
    }
}